public class LeetCode1658 {
    public int minOperations(int[] nums, int x) {
        int sum = 0;
        for (int i : nums) {
            sum += i;
        }
        int target = sum - x;
        int n = nums.length;
        int len = 0;
        Boolean flag = false;
        for (int i = 0; i < n; i++) {
            int j = i;
            sum = 0;
            for (; j < n; j++) {
                if (sum >= target) {
                    break;
                } else {
                    sum += nums[j];
                }
            }
            if (sum == target) {
                len = Math.max(len, j - i);
                flag = true;
            }
        }
        if (!flag) {
            return -1;
        } else {
            return n - len;
        }
    }

    public int minOperations2(int[] nums, int x) {
        int sum = 0;
        for (int i : nums) {
            sum += i;
        }
        int target = sum - x;
        if (target < 0) {
            return -1;
        } else if (target == 0) {
            return nums.length;
        }
        sum = 0;
        int n = nums.length;
        int len = 0;
        Boolean flag = false;
        int left = 0;
        int right = 0;
        while (right < n) {
            sum += nums[right++];
            while (sum > target && left < right) {
                sum -= nums[left++];
            }
            if (sum == target) {
                len = Math.max(len, right - left);
                flag = true;
            }
        }
        if (!flag) {
            return -1;
        } else {
            return n - len;
        }
        // return n - len;
    }
}
